<template>
  <div class="app-container">
    <!-- 添加或修改岗位对话框 -->
    <el-form
      v-if="type == 'add' || type == 'edit'"
      @submit.native.prevent
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="公告标题" prop="noticeTitle">
            <div v-if="type === 'detail' || type === 'preview'">
              {{ form.noticeTitle }}
            </div>
            <el-input
              v-else
              v-model="form.noticeTitle"
              placeholder="请输入公告标题"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公告时间" prop="endTime">
            <el-date-picker
              @blur="changeTime($event, 'startTime')"
              type="datetime"
              :disabled="type === 'detail' || type === 'preview'"
              style="margin: 0 5px 0 15px"
              v-model="form.startTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
            <span>至</span>
            <el-date-picker
              @blur="changeTime($event, 'endTime')"
              type="datetime"
              :disabled="
                type === 'detail' || type === 'preview' || !form.startTime
              "
              style="margin-left: 5px"
              v-model="form.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="收件人" prop="receiverList">
        <el-checkbox-group
          :disabled="type == 'detail' || type === 'preview'"
          v-model="form.receiverList"
        >
          <el-checkbox label="1">教务平台</el-checkbox>
          <el-checkbox label="2">教师端</el-checkbox>
          <el-checkbox label="3">学生端</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="公告内容" prop="noticeContent">
        <input
          style="display: none"
          class="uploadContain_input"
          type="file"
          accept=".pdf, .docx, .doc,.xls ,.xlsx"
          ref="fileInput1"
          @change="uploadFile($event)"
          multiple
        />
        <div class="addFile">
          <div
            class="handelAddFile flex shou"
            @click="handleUpload()"
            v-if="type !== 'detail' || type !== 'preview'"
          >
            <img src="@/assets/images/upload/upload.png" alt="加载失败"/>上传文件
          </div>
          <div
            class="fileName shou flex"
            @click="openFile(item.url)"
            v-for="(item, index) in form.noticeFiles"
            :key="index"
          >
            <img :src="returnIcon(item.url, 1)" alt="加载失败" class="icon"/>
            <div>{{ item.name }}</div>
            <img
              v-if="type !== 'detail' && type !== 'preview'"
              style="width: 16px; height: 16px"
              src="@/assets/images/upload/reddel.png"
              alt="加载失败"
              @click.stop="delFile(index)"
            />
          </div>
          <!-- <div  class="addFileTip">仅支持扩展名：.doc .docx .pdf .xls .xlsx</div> -->
        </div>
        <div
          v-if="type === 'detail' || type == 'preview'"
          v-html="form.noticeContent"
        ></div>
        <wangEditor v-else :editorValue.sync="form.noticeContent"></wangEditor>
      </el-form-item>
    </el-form>
    <div class="card" v-else>
      <div class="title">{{ form.noticeTitle }}</div>
      <div class="content" v-html="form.noticeContent"></div>
      <div
        v-if="form.noticeFiles.length > 0"
        class="file shou dis"
        @click="to(item.url)"
        v-for="(item, index) in form.noticeFiles"
        :key="index"
      >
        <img :src="returnIcon(item.url, 1)" alt="加载失败" class="icon"/>
        {{ item.name }}
      </div>
    </div>
    <div style="height: 70px"></div>
    <div class="bottom">
      <!-- publisSstatus：0草稿，1发布（这个状态下看notice_status的状态）
        noticeStatus：0待发布，1已发布，2已结束 -->
      <el-button
        @click="cancel"
        v-if="
          type == 'add' ||
          (type == 'edit' && form.publishStatus == 0) ||
          (type == 'edit' && form.publishStatus == 1 && form.noticeStatus == 0)
        "
      >退 出
      </el-button
      >
      <el-button
        @click="cancel"
        v-if="
          type == 'detail' ||
          type == 'preview' ||
          (type == 'edit' && form.publishStatus == 1 && form.noticeStatus == 1)
        "
      >关 闭
      </el-button
      >

      <el-button
        v-if="type !== 'preview' && type !== 'detail'"
        v-preventReClick
        type="primary"
        @click="preview()"
      >预 览
      </el-button
      >
      <el-button
        v-preventReClick
        type="primary"
        @click="submitForm('saveAndExit')"
        v-if="type == 'add' || (type == 'edit' && form.publishStatus == 0)"
      >保存并退出
      </el-button
      >
      <el-button
        v-preventReClick
        type="primary"
        @click="submitForm('saveAndpublish')"
        v-if="type == 'add' || (type == 'edit' && form.publishStatus == 0)"
      >发布并退出
      </el-button
      >
      <el-button
        v-preventReClick
        type="primary"
        @click="submitForm('quash')"
        v-if="type == 'edit' && form.publishStatus == 1"
      >撤销发布
      </el-button
      >
      <el-button
        v-preventReClick
        type="primary"
        @click="submitForm('quash')"
        v-if="type == 'edit' && form.publishStatus == 2"
      >撤销
      </el-button
      >
    </div>
  </div>
</template>

<script>
import { returnIcon } from '@/utils/util.js'
//TODO 只写了全局模板
import wangEditor from '@/components/Editor/wangEditor.vue'
import router from '@/router'
import {
  addPost_notice,
  updatePost_notice,
  getPost_notice
} from '@/api/notificationCenter/notification'
import { uploadOSS } from '@/api/upload'

export default {
  components: { wangEditor },
  name: 'AddAnnouncementManagement',
  data() {
    return {
      returnIcon: function(url, type) {
        return returnIcon(url, type)
      },
      type: 'add',
      // 表单参数
      form: {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeContent: undefined,
        noticeType: 2,
        startTime: '',
        endTime: '',
        receiverList: [],
        noticeFiles: '',
        publishStatus: '',
        noticeStatus: '',
        readStatus: false,
        remark: '',
        status: '',
        time: []
      },
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: '公告标题不能为空', trigger: 'blur' }
        ],
        noticeContent: [
          { required: true, message: '公告内容不能为空', trigger: 'blur' }
        ],
        receiverList: [
          { required: true, message: '收件人不能为空', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '公告时间不能为空', trigger: 'blur' }
        ]
      },
      id: undefined
    }
  },
  created() {
    this.type = this.$route.query.type
    if (this.type !== 'add') {
      this.id = this.$route.query.id
      this.getInfo(this.$route.query.id)
      const route = Object.assign({}, this.$route, {
        title: this.type == 'edit' ? '编辑公告' : '公告详情'
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    }
  },
  activated() {
    this.type = this.$route.query.type
    if (this.$route.query.type !== 'add') {
      if (!this.id) {
        this.id = this.$route.query.id
      } else {
        if (this.id != this.$route.query.id) {
          this.id = this.$route.query.id
          this.getInfo(this.$route.query.id)
          const route = Object.assign({}, this.$route, {
            title: this.type == 'edit' ? '编辑公告' : '添加公告'
          })
          this.$store.dispatch('tagsView/updateVisitedView', route)
        }
      }
    } else {
      console.log('add')
      const route = Object.assign({}, this.$route, {
        title: this.type == 'edit' ? '编辑公告' : '添加公告'
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
      if (this.form.noticeId) {
        this.form = {
          noticeId: undefined,
          noticeTitle: undefined,
          noticeContent: undefined,
          noticeType: 2,
          startTime: '',
          endTime: '',
          receiverList: [],
          noticeFiles: [],
          publishStatus: '',
          noticeStatus: '',
          readStatus: false,
          remark: '',
          status: '',
          time: []
        }
      }
    }
  },
  mounted() {
    console.log(this.$route)
  },
  methods: {
    to(url) {
      window.open(url)
    },
    preview() {
      localStorage.setItem('notice', JSON.stringify(this.form))
      this.$router.push({
        path: '/announcement/previewAnnouncementManagement',
        query: {
          type: 'preview'
        }
      })
    },
    cancel() {
      this.$store.dispatch('tagsView/delView', router.currentRoute)
      // 返回上一页
      setTimeout(() => {
        this.$router.push({ path: '/announcement/announcementManagement' })
      }, 100)
    },
    getInfo(id) {
      getPost_notice(id).then((response) => {
        response.data.noticeFiles = response.data.noticeFiles
          ? JSON.parse(response.data.noticeFiles)
          : []
        response.data.time = [response.data.startTime, response.data.endTime]
        let receiverList = []
        if (
          response.data.receiverList.find((item) => {
            return item.roleId == 5
          })
        ) {
          receiverList.push('1')
        }
        if (
          response.data.receiverList.find((item) => {
            return item.roleId == 3
          })
        ) {
          receiverList.push('2')
        }
        if (
          response.data.receiverList.find((item) => {
            return item.roleId == 4
          })
        ) {
          receiverList.push('3')
        }
        console.log(receiverList)
        response.data.receiverList = receiverList
        this.form = response.data
      })
    },
    changeTime(e, key) {
      if (key == 'startTime') {
        const currentTime = new Date().getTime()
        const minStartTime = currentTime - 1000
        if (new Date(this.form.startTime).getTime() < minStartTime) {
          this.$notify.error('公告开始时间不能早于当前时间')
          this.form.startTime = undefined
        }
      } else {
        if (new Date(this.form.endTime) < new Date(this.form.startTime)) {
          this.$notify.error('公告结束时间不能早于公告开始时间')
          this.form.endTime = undefined
        }
      }
    },
    handleUpload() {
      this.$refs.fileInput1.click()
    },
    openFile(url) {
      window.open(url)
    },
    delFile(index) {
      this.form.noticeFiles.splice(index, 1)
    },
    /* 上传文件 */
    async uploadFile(event) {
      let files = event.target.files
      let formData = new FormData()
      for (let i = 0; i < Array.from(files).length; i++) {
        formData.append(
          'files',
          new File([Array.from(files)[i]], Array.from(files)[i].name)
        )
      }
      const currentDate = new Date()
      const year = currentDate.getFullYear()
      const month = String(currentDate.getMonth() + 1).padStart(2, '0')
      const day = String(currentDate.getDate()).padStart(2, '0')

      const formattedDate = `${year}/${month}/${day}`
      let res = await uploadOSS(
        files,
        `cloud/notice/${formattedDate}`,
        true,
        event
      )
      this.form.noticeFiles = [...this.form.noticeFiles, ...res]
      event.target.value = ''
      this.$notify.success('上传成功')
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs['form'].clearValidate()
      this.$forceUpdate()

      if (type == 'saveAndpublish') {
        this.rules = {
          noticeTitle: [
            { required: true, message: '公告标题不能为空', trigger: 'blur' }
          ],
          noticeContent: [
            { required: true, message: '公告内容不能为空', trigger: 'blur' }
          ],
          receiverList: [
            { required: true, message: '收件人不能为空', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '公告时间不能为空', trigger: 'blur' }
          ]
        }
      } else {
        this.rules = {
          noticeTitle: [
            { required: true, message: '公告标题不能为空', trigger: 'blur' }
          ]
        }
      }

      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 保存并退出
          if (type == 'saveAndExit') {
            this.fun(type)
          }
          // 保存并发布
          else if (type == 'saveAndpublish') {
            this.$confirm(
              `确定发布【${this.form.noticeTitle}】
              吗？同一时间仅展示一条公告信息（取开始时间早的公告）`,
              '发布确认',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              this.fun(type)
            })
          }
          // 撤销
          else {
            this.$confirm(
              `确定撤销【${this.form.noticeTitle}】吗？撤销后可重新编辑`,
              '撤销确认',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              this.fun(type)
            })
          }
        }
      })
    },
    fun: function(type) {
      let data = JSON.parse(JSON.stringify(this.form))
      let receiverList = []
      if (this.form.receiverList.includes('1')) {
        receiverList = [
          ...receiverList,
          ...[{ roleId: 5 }, { roleId: 6 }, { roleId: 9 }]
        ]
      }
      if (this.form.receiverList.includes('2')) {
        receiverList.push({ roleId: 3 })
      }
      if (this.form.receiverList.includes('3')) {
        receiverList.push({ roleId: 4 })
      }

      data.receiverList = receiverList
      data.noticeFiles = JSON.stringify(data.noticeFiles)
      if (this.form.noticeId != undefined) {
        // 保存并退出
        if (type == 'saveAndExit') {
          data.publishStatus = 0
          data.noticeStatus = 0
        }
        // 保存并发布
        else if (type == 'saveAndpublish') {
          data.publishStatus = 1
          data.noticeStatus = 0
        }
        // 撤销
        else {
          data.publishStatus = 0
          data.noticeStatus = 0
        }
        updatePost_notice(data).then(() => {
          if (type == 'saveAndExit') {
            this.$modal.msgSuccess('保存成功')
          } else {
            this.$modal.msgSuccess('发布成功')
          }

          // 返回上一页
          this.$store.dispatch('tagsView/delView', router.currentRoute)
          setTimeout(() => {
            this.$router.push({ path: '/announcement/announcementManagement' })
          }, 100)
        })
      } else {
        // 保存并退出
        if (type == 'saveAndExit') {
          data.publishStatus = 0
          data.noticeStatus = 0
        }
        // 保存并发布
        else {
          data.publishStatus = 1
          data.noticeStatus = 0
        }
        addPost_notice(data).then(() => {
          if (type == 'saveAndExit') {
            this.$modal.msgSuccess('保存成功')
          } else {
            this.$modal.msgSuccess('发布成功')
          }
          // 返回上一页
          this.$store.dispatch('tagsView/delView', router.currentRoute)
          setTimeout(() => {
            this.$router.push({ path: '/announcement/announcementManagement' })
          }, 100)
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
.card {
  .title {
    text-align: center;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 500;
    font-size: 18px;
    color: #333333;
    line-height: 22px;
    font-style: normal;
  }

  .time {
    margin-top: 16px;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 14px;
    color: #999999;
    line-height: 20px;
    text-align: left;
    font-style: normal;
  }

  .content {
    width: 1200px;
    margin-top: 32px;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    line-height: 22px;
    text-align: left;
    font-style: normal;
    white-space: pre-wrap;
    word-wrap: break-word;
  }

  .file:hover {
    color: #333333;
  }

  .file {
    margin-top: 32px;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #1b64ff;
    line-height: 22px;
    text-align: left;
    font-style: normal;
    text-decoration-line: underline;
  }
}

.bottom {
  box-sizing: border-box;
  padding: 15px 20px 15px 0;
  background: white;
  width: 100%;
  height: 70px;
  display: flex;
  justify-content: flex-end;
  position: fixed;
  bottom: 0;
  right: 0;
}

.addFile {
  padding-bottom: 20px;

  .handelAddFile {
    margin-bottom: 10px;
    width: 112px;
    height: 32px;
    background: #ffffff;
    border-radius: 6px;
    border: 1px solid rgba(0, 0, 0, 0.15);

    margin-left: 1px;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    line-height: 32px;
    text-align: left;
    font-style: normal;

    img {
      margin: 7px 6px 0 14px;
      width: 16px;
      height: 16px;
    }
  }

  .fileName {
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 500;
    font-size: 16px;
    color: #1b64ff;

    .icon {
      margin: 6px 6px 0 0;
      width: 20px;
      height: 20px;
    }
  }

  .addFileTip {
    margin-left: 12px;
    height: 32px;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 14px;
    line-height: 40px;
    text-align: right;
    font-style: normal;
  }
}
</style>
